﻿package  Cain.pcxbook
{
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.events.ProgressEvent;
	import flash.utils.ByteArray;
	/**
	 * 漸進式圖片載入
	 * @author Cain
	 */
	public class BigLoader extends Sprite{
		private var loader:Loader;
		private var stream:URLStream;
		private var bytes:ByteArray = new ByteArray();
		public function BigLoader()
		{
			setup();
		}
		
		private function setup():void
		{
			loader = new Loader();
			addEventListener(Event.ADDED_TO_STAGE, addthis);
			stream = new URLStream();
			stream.addEventListener(ProgressEvent.PROGRESS, stream_onPROGRESS);
			stream.addEventListener(Event.COMPLETE, stream_onCOMPLETE);
		}
		
		private function stream_onCOMPLETE(e:Event):void 
		{
			if (stream.connected)
			{
				stream.close();
				stream = null;
				bytes = null;
			}
		}
		
		private function stream_onPROGRESS(e:ProgressEvent):void 
		{
			if (stream.bytesAvailable == 0)
			{
				return;
			}else if (stream.connected)
			{
				stream.readBytes(bytes, bytes.length);
				loader.unload();
				loader.loadBytes(bytes);
			}
		}
		
		private function addthis(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, addthis);
			addEventListener(Event.REMOVED_FROM_STAGE, renovethis);
			init();
		}
		
		private function init():void
		{
			addChild(loader);
		}
		public function load(_url:String):void 
		{
			stream.load(new URLRequest(_url));
		}
		private function renovethis(e:Event):void 
		{
			removeEventListener(Event.REMOVED_FROM_STAGE, renovethis);
		}
	}
	
}